﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApiTest.Dto.Basic;
using WebApiTest.Dto.Utils;
using WebApiTest.Models;

namespace WebApiTest.Service.Basic

{
    public class DeptService
    {
        officeContext db = new officeContext();

        public TableRspDTO list4Table(TableReqDTO tableReqDTO)
        {
            long count = db.Dept
                .Where(u => string.IsNullOrEmpty(tableReqDTO.parseQueryParam("deptName")) || u.DeptName.Contains(tableReqDTO.parseQueryParam("deptName")))
                .LongCount();
            List<JObject> res = db.Dept
                .Select(u => new { key = u.DeptId, deptId = u.DeptId, deptName = u.DeptName })
                .Where(u => string.IsNullOrEmpty(tableReqDTO.parseQueryParam("deptName")) || u.deptName.Contains(tableReqDTO.parseQueryParam("deptName")))
                .OrderByDescending(u => u.deptId)
                .Skip(tableReqDTO.getStart())
                .Take(tableReqDTO.pageSize)
                .ToList()
                .ConvertAll(r => JObject.FromObject(r));
            PagingDTO pagingDTO = new PagingDTO(
                tableReqDTO.pageNo,
                tableReqDTO.pageSize,
                count,
                res
                );
            return new TableRspDTO(pagingDTO);
        }

        public int add(Dept dept)
        {
            db.Dept.Add(dept);
            db.SaveChanges();
            return 1;
        }

        public int update(Dept dept)
        {
            Dept o = db.Dept.Find(dept.DeptId);
            o.DeptName = dept.DeptName;
            db.SaveChanges();
            return 1;
        }
        public int remove(string ids)
        {
            List<Dept> list = new List<Dept>();
            string[] idList = ids.Split(",");
            foreach (string id in idList)
            {
                list.Add(db.Dept.Find(long.Parse(id)));
            }
            db.Dept.RemoveRange(list);
            //更新到数据库
            db.SaveChanges();
            return list.Count();
        }

        public List<JObject> listAll()
        {
            return db.Dept
                .Select(e => new { deptId = e.DeptId, deptName = e.DeptName })
                .ToList()
                .ConvertAll(e => JObject.FromObject(e)); 
        }

    }
}
